package com.sunleader.netboot.module.config;

import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

import java.io.File;

@Configuration
public class FTPConfig implements ApplicationRunner {
    @Value("${ftp.homePath:/opt/pypxe-plus/netboot/}")
    private String homePath;
    @Value("${user.path:/opt/pypxe-plus/user.porperties}")
    private String userPath;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        FtpServerFactory serverFactory = new FtpServerFactory();
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        File file = new File(userPath);
        if(!file.exists()){
            file.createNewFile();
        }
        userManagerFactory.setFile(file);
        UserManager userManager = userManagerFactory.createUserManager();

        BaseUser anonymousUser = new BaseUser();
        anonymousUser.setName("anonymous");
        anonymousUser.setHomeDirectory(homePath);
        userManager.save(anonymousUser);

        serverFactory.setUserManager(userManager);
        FtpServer server = serverFactory.createServer();
        server.start();
    }
}
